package com.agency8x.model;

import java.util.ArrayList;
import java.util.List;

import com.agency8x.model.base.BaseAuthRuleModel;
import com.agency8x.model.base.BaseMenuItemModel;
import com.agency8x.util.RegexUtil;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

public class AuthRuleModel extends BaseAuthRuleModel<AuthRuleModel> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public static final AuthRuleModel me = new AuthRuleModel().dao();

	/**
	 * 所有 sql 与业务逻辑写在 Service 中，在此放在 Model 中仅为示例
	 */
	public Page<AuthRuleModel> paginate(int pageNumber, int pageSize, String where) {
		String sql = "select * ";
		String sqlFrom = "from t_auth_rule";
		if (where != null && !"".equals(where.trim())) {
			if (RegexUtil.isNumeric(where))
				sqlFrom = sqlFrom + "where id = " + where;
		}
		return paginate(pageNumber, pageSize, sql, sqlFrom);
	}

	public AuthRuleModel adminEdit(String where) {
		return me.findFirst("select * from t_auth_rule where user_id = ?", where);
	}

	public List<BaseMenuItemModel> getMenus(Integer user_id) {
		String rules = AdminModel.me.getAuthRules(user_id); 
		String where = StrKit.isBlank(rules) ? "" : " where id in (" + rules + ")";
		List<BaseMenuItemModel> miList2, miList3, miList = new ArrayList<BaseMenuItemModel>();
		List<AuthRuleModel> list1 = this.find("select * from t_auth_rule" + where);
		BaseMenuItemModel mi1, mi2, mi3;
		int id1, id2, pid2, pid3;
		for (AuthRuleModel m1 : list1) {
			if (m1.getPid() == 0) {
				id1 = m1.getId();
				mi1 = new BaseMenuItemModel(id1, m1.getTitle(), "");
				miList2 = new ArrayList<BaseMenuItemModel>();
				for (AuthRuleModel m2 : list1) {
					id2 = m2.getId();
					pid2 = m2.getPid();
					if (pid2 == id1) {
						mi2 = new BaseMenuItemModel(m2.getId(), m2.getTitle(), m2.getUrl());
						miList2.add(mi2);
						miList3 = new ArrayList<BaseMenuItemModel>();
						for (AuthRuleModel m3 : list1) {
							pid3 = m3.getPid();
							if (pid3 == id2) {
								mi3 = new BaseMenuItemModel(m3.getId(), m3.getTitle(), m3.getUrl());
								miList3.add(mi3);
							}
						}
						mi2.setChildren(miList3);
					}
				}
				mi1.setChildren(miList2);
				miList.add(mi1);
			}
		}
		return miList;
	}

	public List<Record> getRecordByPid(int pid, int userId) {
		String rules = AdminModel.me.getAuthRules(userId);
		String inIdsSql = StrKit.isBlank(rules) ? "" : " and id in (" + rules + ")";
		System.out.print("======================="+(StrKit.isBlank(rules)?"null"+userId:rules));
		System.out.print("======================="+inIdsSql);
		return Db.find("select id, title, rule_name, url from t_auth_rule where pid=?" + inIdsSql, pid);
	}
}
